package com.zqh.common.xss;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * XSS过滤
 *
 * @author wangzheng
 * @email wangzheng19851019@163.com
 * @url www.sungohealth.com
 * @date 2017年8月8日 下午12:00:23
 */
public class XssFilter implements Filter {

	@Override
	public void init(FilterConfig config) throws ServletException {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
		XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(
				(HttpServletRequest) request);


		HttpServletResponse servletResponse = (HttpServletResponse) response;

		String []  allowDomain= {"http://47.104.171.115","http://47.104.84.244","http://localhost:63342","http://192.168.2.185:8020"};
		Set allowedOrigins= new HashSet(Arrays.asList(allowDomain));
		String originHeader=((HttpServletRequest) xssRequest).getHeader("Origin");
		if (allowedOrigins.contains(originHeader)) {
			servletResponse.setHeader("Access-Control-Allow-Origin", originHeader);
			servletResponse.setContentType("application/json;charset=UTF-8");
			servletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
			servletResponse.setHeader("Access-Control-Max-Age", "3600");
			servletResponse.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");//表明服务器支持的所有头信息字段
			servletResponse.setHeader("Access-Control-Allow-Credentials", "true"); //如果要把Cookie发到服务器，需要指定Access-Control-Allow-Credentials字段为true;
			servletResponse.setHeader("XDomainRequestAllowed", "1");
		}
		chain.doFilter(xssRequest, servletResponse);
	}

	@Override
	public void destroy() {
	}

}